package com.ruoyi.platform.system.role.manager;

import com.ruoyi.base.enums.ExceptionEnum;
import com.ruoyi.base.exception.SysException;
import com.ruoyi.base.service.BaseService;
import com.ruoyi.platform.system.role.dao.UserRoleDAO;
import com.ruoyi.platform.system.role.enums.FunctionEnum;
import com.ruoyi.platform.system.role.enums.RoleEnum;
import com.ruoyi.platform.system.role.pojo.UserRoleDO;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色
 *
 * @author lcf
 */
@Component
public class RoleManager extends BaseService {
    @Autowired
    private UserRoleDAO userRoleDAO;

    /**
     * 检查用户权限
     */
    public void checkUserRole(long userId, FunctionEnum function) {
        if (function == null) {
            return;
        }

        if (CollectionUtils.isEmpty(function.getRoleCodeList())) {
            throw new SysException(ExceptionEnum.NO_PERMISSION);
        }

        List<Integer> roleCodeList = function.getRoleCodeList().stream().map(RoleEnum::getCode).collect(Collectors.toList());
        int count = userRoleDAO.checkUserRole(userId, roleCodeList);
        if (count <= 0) {
            throw new SysException(ExceptionEnum.NO_PERMISSION);
        }
    }

    /**
     * 检查角色code
     */
    public List<RoleEnum> checkCode(List<Integer> roleCodeList) {
        if (CollectionUtils.isEmpty(roleCodeList)) {
            return emptyList();
        }

        return roleCodeList.stream().map(RoleEnum::checkRoleCode).collect(Collectors.toList());
    }

    /**
     * 修改用户角色
     */
    public void setUserRole(long userId, List<RoleEnum> roleList) {
        userRoleDAO.delByUserId(userId);

        if (CollectionUtils.isEmpty(roleList)) {
            return;
        }

        List<UserRoleDO> list = roleList.stream().map(x -> new UserRoleDO(userId, x)).collect(Collectors.toList());
        userRoleDAO.insertUserRoleSelectiveBatch(list);
    }
}
